package com.neusoft.his.sys.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.his.sys.entity.CommonResult;
import com.neusoft.his.sys.entity.Emp;
import com.neusoft.his.sys.entity.Pictures;
import com.neusoft.his.sys.service.IEmpService;
import com.neusoft.his.sys.util.JwtToken;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 东软教育集团
 * @since 2022-08-24
 */
@RestController
@RequestMapping("/emp")
@CrossOrigin("*")
public class EmpController {
	@Autowired
	IEmpService empService;
	
	@RequestMapping("/loginneeded")
	public CommonResult loginneeded() {
		return CommonResult.ret403();
	}
	
//	http://127.0.0.1:18080/his/emp/login 
	@PostMapping("/login")
	public CommonResult login(@RequestBody Emp emp) {
		emp.setToken( JwtToken.generateToken(emp));
		return  new  CommonResult<Emp>(emp);
	}
	
	

	@PostMapping("/upload")
	public CommonResult imporDate(MultipartFile file, HttpServletRequest request, Pictures pictures)
			throws IOException {
		if (file != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 获取当前日期为保存文件的目录名
			String newFileDate = sdf.format(new Date());
			// 获取static文件夹所在的位置,并在static下创建upload目录，在upload目录下创建newFileDate目录用于保存图片
			String realPath = request.getServletContext().getRealPath("/upload/" + newFileDate);
			// 通过获取到的路径创建目录
			File folder = new File(realPath);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			// 给文件重命名
			// 获取原有的文件名
			String oldFolderName = file.getOriginalFilename();
			// 生成新的文件名
			String newFolderName = UUID.randomUUID() + oldFolderName.substring(oldFolderName.lastIndexOf("."));
			// 保存文件到newFileDate目录下，并命名为newFolderName
			file.transferTo(new File(folder, newFolderName));
			// 获取文件的相关参数保存至数据库中
			String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ "/his/upload" + "/" + newFileDate + "/" + newFolderName;
			pictures.setUrl(url);
			pictures.setId((int) new Date().getTime());
			System.out.println(url);
			System.out.println(pictures.toString());
			// 这里调用service。。。
			return new CommonResult(pictures);
		} else {
			return new CommonResult(1);
		}
	}

//	http://127.0.0.1:18080/his/emp/all
	@GetMapping("/all")
	public CommonResult getAll() {
		CommonResult result = empService.getAll();
		return result;
	}

}
